<template>
  <div class="question-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">problem</h1>
        <div class="page-description">Discover and answer interesting questions</div>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="goToAsk">
          <el-icon><Plus /></el-icon>
          question
        </el-button>
      </div>
    </div>

    <!-- 筛选和排序 -->
    <div class="filter-bar">
      <div class="filter-tabs">
        <button
          v-for="tab in sortTabs"
          :key="tab.value"
          class="filter-tab"
          :class="{ active: currentSort === tab.value }"
          @click="handleSortChange(tab.value)"
        >
          {{ tab.label }}
        </button>
      </div>

      <div class="filter-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="Search questions..."
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 问题列表 -->
    <div class="question-list" v-loading="loading">
      <QuestionCard
        v-for="question in questionList"
        :key="question.id"
        :question="question"
        @follow="handleQuestionFollow"
        @like="handleQuestionLike"
        @share="handleQuestionShare"
      />

      <!-- 空状态 -->
      <div v-if="!loading && questionList.length === 0" class="empty-state">
        <el-empty description="No problem">
          <el-button type="primary" @click="goToAsk">Publish the first question</el-button>
        </el-empty>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import QuestionCard from '@/components/QuestionCard.vue'
import {getQuestionList} from '@/api/question'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const questionList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const currentSort = ref('latest')
const searchKeyword = ref('')

// 排序选项
const sortTabs = [
  { label: 'latest', value: 'latest' },
  { label: 'hot', value: 'hot' },
  { label: 'unanswered', value: 'unanswered' }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sortType: 'latest',
  keyword: '',
  topicId: '',
  userId: '',
  onlyFollowed: false
})

// 获取问题列表
const fetchQuestionList = async () => {
  loading.value = true
  try {
    const response = await getQuestionList({
      ...queryParams,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      sortType: currentSort.value,
      keyword: searchKeyword.value
    })

    if (response.code === 200) {
      questionList.value = response.data.data || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取问题列表失败:', error)
    ElMessage.error('获取问题列表失败')
  } finally {
    loading.value = false
  }
}

// 处理排序变化
const handleSortChange = (sortType) => {
  currentSort.value = sortType
  currentPage.value = 1
  fetchQuestionList()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchQuestionList()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchQuestionList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchQuestionList()
}

// 跳转到提问页面
const goToAsk = () => {
  router.push('/ask')
}

// 处理问题关注
const handleQuestionFollow = (questionId, isFollowed) => {
  const question = questionList.value.find(q => q.id === questionId)
  if (question) {
    question.isFollowed = isFollowed
    question.followCount += isFollowed ? 1 : -1
  }
}

// 处理问题点赞
const handleQuestionLike = (questionId, isLiked) => {
  const question = questionList.value.find(q => q.id === questionId)
  if (question) {
    question.isLiked = isLiked
    question.likeCount += isLiked ? 1 : -1
  }
}

// 处理问题分享
const handleQuestionShare = (question) => {
  // 复制分享链接到剪贴板
  const url = `${window.location.origin}/question/${question.id}`
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('分享链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 监听搜索关键词变化
watch(searchKeyword, (newVal, oldVal) => {
  if (newVal !== oldVal && newVal === '') {
    handleSearch()
  }
})

// 页面加载时获取数据
onMounted(() => {
  fetchQuestionList()
})
</script>

<style lang="scss" scoped>
.question-page {
  padding: 0;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
  padding: 24px 0;
  border-bottom: 1px solid $border-light;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: $text-color;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 16px;
  color: $text-secondary;
}

.header-right {
  .el-button {
    padding: 12px 24px;
    font-size: 15px;
  }
}

.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
  padding: 20px 0;
  background: $background-color;
  border-radius: $border-radius-large;
  padding: 20px 24px;
  box-shadow: $shadow-light;
}

.filter-tabs {
  display: flex;
  gap: 8px;
}

.filter-tab {
  background: none;
  border: none;
  padding: 10px 20px;
  border-radius: $border-radius-medium;
  font-size: 15px;
  color: $text-secondary;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    color: $text-color;
    background-color: $background-light;
  }

  &.active {
    color: $primary-color;
    background-color: rgba(0, 132, 255, 0.1);
    font-weight: 500;
  }
}

.filter-actions {
  .search-input {
    width: 300px;
  }
}

.question-list {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding-top: 24px;
  border-top: 1px solid $border-light;
}
</style>
